{% extends "base.html" %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <h1 class="text-2xl font-bold mb-6">Model Call Records</h1>
    
    <!-- Date Filter -->
    <div class="mb-6 flex gap-4">
        <div>
            <label class="block text-sm font-medium mb-1">Start Date</label>
            <input type="date" id="startDate" class="border rounded px-3 py-2">
        </div>
        <div>
            <label class="block text-sm font-medium mb-1">End Date</label>
            <input type="date" id="endDate" class="border rounded px-3 py-2">
        </div>
        <div class="flex items-end">
            <button onclick="filterRecords()" class="bg-blue-500 text-white px-4 py-2 rounded">
                Filter
            </button>
        </div>
    </div>

    <!-- Records Table -->
    <div class="overflow-x-auto">
        <table class="min-w-full bg-white border rounded-lg">
            <thead class="bg-gray-50">
                <tr>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Timestamp
                    </th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Type
                    </th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Model
                    </th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Duration (ms)
                    </th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Status
                    </th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        Details
                    </th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-200" id="recordsTable">
                <!-- Records will be inserted here -->
            </tbody>
        </table>
    </div>
</div>

<script>
// Add helper function for JSON formatting
function formatJSON(data) {
    if (typeof data === 'string') {
        try {
            // Try to parse if it's a JSON string
            return JSON.stringify(JSON.parse(data), null, 2);
        } catch (e) {
            // If not valid JSON, return as is
            return data;
        }
    }
    // If already an object, stringify with formatting
    return JSON.stringify(data, null, 2);
}

// Add helper function for messages formatting
function formatMessages(request) {
    if (!request || !request.messages) return '';
    return request.messages.map(msg => 
        `${msg.role}: ${msg.content.replace(/\\n/g, '\n')}`
    ).join('\n\n');
}

async function loadRecords(startDate = '', endDate = '') {
    try {
        const params = new URLSearchParams();
        if (startDate) params.append('start_date', startDate);
        if (endDate) params.append('end_date', endDate);
        
        const response = await fetch(`/api/model-calls?${params}`);
        const records = await response.json();
        
        const tbody = document.getElementById('recordsTable');
        tbody.innerHTML = records.map(record => `
            <tr class="hover:bg-gray-50">
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    ${new Date(record.timestamp).toLocaleString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit',
                        second: '2-digit',
                        hour12: false
                    })}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    ${record.type}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    ${record.request?.model || 'N/A'}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    ${record.duration_ms}
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                        ${record.error ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'}">
                        ${record.response === null ? 'Error' : 'Success'}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <button onclick="toggleDetails(this)" class="text-blue-600 hover:text-blue-800">
                        Show Details
                    </button>
                </td>
            </tr>
            <tr class="hidden">
                <td colspan="6" class="px-6 py-4 bg-gray-50">
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <h3 class="font-semibold mb-2">Input:</h3>
                            <pre class="bg-white p-3 rounded border text-sm overflow-x-auto">
${record.request ? formatMessages(record.request) : 'No input data'}
                            </pre>
                        </div>
                        <div>
                            <h3 class="font-semibold mb-2">Output:</h3>
                            <pre class="bg-white p-3 rounded border text-sm overflow-x-auto">
${formatJSON(record.response) || formatJSON(record.error) || 'No output data'}
                            </pre>
                        </div>
                    </div>
                </td>
            </tr>
        `).join('');
    } catch (error) {
        console.error('Error loading records:', error);
    }
}

function toggleDetails(button) {
    const detailsRow = button.closest('tr').nextElementSibling;
    const isHidden = detailsRow.classList.contains('hidden');
    detailsRow.classList.toggle('hidden');
    button.textContent = isHidden ? 'Hide Details' : 'Show Details';
}

function filterRecords() {
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    loadRecords(startDate, endDate);
}

// Load initial records
loadRecords();
</script>
{% endblock %}
